package cmd

import (
	"fmt"
	"os"
	"path"

	"gitee.com/xuender/oils/logs"
	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// nolint: gochecknoglobals
var cfgFile string

// nolint: gochecknoglobals
var rootCmd = &cobra.Command{
	Use:   "files",
	Short: "文件搜索",
	Long:  `索引文件、目录，多种方式进行搜索`,
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	cobra.CheckErr(rootCmd.Execute())
}

// nolint: gochecknoinits
func init() {
	cobra.OnInitialize(initConfig)

	home := logs.PanicString(homedir.Dir())

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "配置文件")
	rootCmd.PersistentFlags().String("db", path.Join(home, ".files"), "数据库目录")
	rootCmd.PersistentFlags().BoolP("debug", "d", false, "调试模式")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		cobra.CheckErr(err)

		viper.AddConfigPath(home)
		viper.AddConfigPath(".")
		viper.SetConfigType("toml")
		viper.SetConfigName("files")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
	}
}
